import React, { useState } from 'react';
import BraftEditor from 'braft-editor';
import { message } from 'antd';
import { uploadFile } from './fileUpload';

const RichText = React.forwardRef((props, ref) => {
    const { onChange, value, limitWidth, checkFileSize = 0 } = props;
    const [imgWidth, setImgWidth] = useState(5000);
    React.useEffect(() => {
        setImgWidth(limitWidth);
    }, [limitWidth]);

    // 编辑器上传图片的操作
    const myUploadFn = param => {
        const params = {
            fileInfo: param
        };
        return uploadFile(params);
    };
    const myValidateFn = file =>
        new Promise((resolve, reject) => {
            if (checkFileSize > 0) {
                const isLess = file.size / 1024 / 1024 < checkFileSize;
                if (!isLess) {
                    message.error(`文件不能大于 ${checkFileSize}MB!`);
                    reject();
                }
            }
            if (file.type === 'video/mp4' || file.type === 'video/mp3') {
                resolve();
            } else {
                const reader = new FileReader();

                reader.onload = e => {
                    const data = e.currentTarget.result;
                    // 加载图片获取图片真实宽度和高度
                    const image = new Image();
                    image.onload = () => {
                        const { width } = image;

                        if (width > imgWidth) {
                            message.error(`宽度不能大于 ${imgWidth}`);
                            reject();
                        } else {
                            resolve();
                        }
                    };
                    image.src = data;
                };
                reader.readAsDataURL(file);
            }
        });
    const handleChange = editorState => {
        onChange(editorState.toHTML(), editorState);
    };

    return (
        <BraftEditor
            ref={ref}
            defaultValue={BraftEditor.createEditorState(value)}
            media={{
                uploadFn: myUploadFn,
                validateFn: myValidateFn,
                accepts: {
                    image: 'image/png,image/jpeg,image/gif'
                }
            }}
            imageControls={['size', 'remove']}
            excludeControls={['fullscreen']}
            style={{
                border: '1px solid #d9d9d9',
                borderTopWidth: '1.02px',
                borderRadius: '4px',
                marginTop: '4px'
            }}
            {...props}
            onChange={handleChange}
        />
    );
});

export default RichText;
